// console.log(window.fetch, 'fetch is ok')

let used = false;
export const useProxyFetch = () => {
  if (used) {
    return console.warn(
      'Proxy fetch has already been used, skipping initialization.',
    );
  }
  used = true;
  const originFetch = window.fetch;
  // 如果是请求mapbox event, 则阻止
  const blockedPrefixList = [
    'https://api.mapbox.com/map-sessions/',
    'https://events.mapbox.com',
  ];
  const proxyFetch = (
    resource: RequestInfo | URL,
    options?: RequestInit,
  ): Promise<Response> => {
    let targetPath = '';
    if (typeof resource === 'string') {
      targetPath = resource;
    } else if (resource instanceof Request) {
      targetPath = resource.url;
    }
    if (
      targetPath &&
      blockedPrefixList.some((prefix) => targetPath.startsWith(prefix))
    ) {
      console.warn('Blocked fetch request to:', targetPath);
      return Promise.reject(
        new Error(`Blocked fetch request to: ${targetPath}`),
      );
    }
    return originFetch(resource, options);
  };
  console.warn(
    `注意注意: 当前已屏蔽部分Event请求, 包括: ${blockedPrefixList.join(', ')}`,
  );
  // 替换全局的 fetch 函数
  window.fetch = proxyFetch;
};
